	
	var selectedTab="manage-civilizations-tab";
	
	$(function() {
	$( "#tabs" ).tabs({
		select: function(event, ui) { 

			var ok = true;
			
			if (selectedTab=="results-tab") ok = storeResultsUI();
			else if (selectedTab=="buy-cards-tab") ok = storeBuyCardsUI();
			else if (selectedTab=="manage-civilizations-tab") ok = storeManageCivilizationsUI();

			selectedTab=ui.panel.id;

			if (!ok) return false;

			updateSelectedUI(selectedTab);

			return true;
			
		;}
		});
	});
	
	function updateSelectedUI(activePage) {

		if (activePage=="results-tab") updateResultsUI();
		else if (activePage=="buy-cards-tab") updateBuyCardsUI();
		else if (activePage=="manage-civilizations-tab") updateManageCivilizationsUI();

	}

	
	var selectedManageCivilization=null;
	
	$(function() {
	$( "#manage-civilizations-accordion" ).accordion({
		change: function(event, ui) { 
		
			if (ui.newContent.length>0) {
				selectedManageCivilization = ui.newContent[0].id.split("-")[1];
			}
			else {
				selectedManageCivilization=null;
			}
			var previous = null;
			if (ui.oldContent.length>0) previous = ui.oldContent[0].id;

			if (previous!=null) {
				storeManageCivilizationForm(previous.split("-")[1]);
			}
			if (selectedManageCivilization!=null) {
				updateManageCivilizationForm(selectedManageCivilization);
			}
		   }
		});
	});

	var selectedBuyCardsCivilization=null;
	
	$(function() {
	$( "#buy-cards-accordion" ).accordion({
		change: function(event, ui) { 
			
			if (ui.newContent.length>0) {
				selectedBuyCardsCivilization = ui.newContent[0].id.split("-")[1];
			}
			else {
				selectedBuyCardsCivilization=null;
			}

			var previous = null;
			if (ui.oldContent.length>0) previous = ui.oldContent[0].id;

			if (previous!=null) {
				storeBuyCardsForm(previous.split("-")[1]);
			}
			if (selectedBuyCardsCivilization!=null) {
				updateBuyCardsForm(selectedBuyCardsCivilization);
			}
		   }
		});
	});

	$(function() {
	$('div#buy-cards-dialog').dialog({
		  /*
			 * position: { my: 'right center', at: 'right center', offset: '-10
			 * 10', of: $(document.window) },
			 */
		  
		  position: 'right',
		  autoOpen:false,
		  buttons: {
				"Save": function() {
			  		storeBuyCardsForm(selectedBuyCardsCivilization);
			  		initializeBuyCards(selectedBuyCardsCivilization);
					showPointsDialog();

				},
				"Reset": function() {
					initializeBuyCards(selectedBuyCardsCivilization);
				}
			
		   },
		   dialogClass: "flora",
		   width:260,
		   minWidth:260,
		   height:290,
		   minHeight:290
	   
		});
	});

	$(function() {
	  $('.flora.ui-dialog').css({position:"fixed"});
	});


	

	// COMMON
	
	var civilizations = new Object();
	var civilizations_actions = new Object();
	
	for (var i=0;i<CIVILIZATIONS_ORDER.length;i++) {
		var civid = CIVILIZATIONS_ORDER[i];
		civilizations[civid]=new Object({player:"", cards: new Array(), astValuePoints:0, citiesPoints:0, treasuryPoints:0, tradeGoodsPoints:0});
		civilizations_actions[civid] = new Array();
	}

	
	function persistCivilizationInformation(civid, civData, callback) {

		log("storing civilization information: "+civid);
		log(civData);

		civilizations[civid].player=civData.player;	
		civilizations[civid].astValuePoints=civData.astValuePoints;
		civilizations[civid].citiesPoints=civData.citiesPoints;
		civilizations[civid].treasuryPoints=civData.treasuryPoints;
		civilizations[civid].tradeGoodsPoints=civData.tradeGoodsPoints;
		
		if (sessionId!=null) {

			var data = new Object();
			data[civid] = civData;
			
			sendCivilizationsInformation(callback,data)
		}
		else {
			callback();
		}
	}


	function persistSelectedCards(civid, cardList, callback) {
		log("storing bought cards: "+civid+" "+cardList);
		
		var addedList = new Array();
		var removedList = new Array();
		var currentList = civilizations[civid].cards;

		for (var i = 0;i<cardList.length;i++) {
			if ($.inArray(cardList[i],currentList)==-1) {
				addedList.push(cardList[i]);
			}
		}
		for (var i = 0;i<currentList.length;i++) {
			if ($.inArray(currentList[i],cardList)==-1) {
				removedList.push(currentList[i]);
			}
		}

		civilizations[civid].cards=cardList;

		log("added list: "+addedList);	
		log("removed list: "+removedList);
		
		if (addedList.length>0 || removedList.length>0) {

			var data = new Object();
			var results = calculateCardPoints(civid);
			var date = new Date();
			var entry = new Object({date:date.getTime(), cards:cardList.length, points:results.points, added:addedList, removed:removedList});
			data[civid] = [entry];

			civilizations_actions[civid].push(entry);			
			
			if (sessionId!=null) {
				sendCivilizationEventInformation(callback,data);
			}else {
				callback();
			}

		}
		else {

			callback();
		}
	}
	

	function sendCivilizationsInformation(callback, data) {
		
		log("sending civilizations information: "+data);
		sendDataAjax(callback, data, "civaid/storeCivilizations");
	}

	function sendCivilizationEventInformation(callback, data) {

		log("sending civilization events information: "+data);
		sendDataAjax(callback, data, "civaid/storeCivilizationEvents");
	}

	function sendDataAjax(callback, data, url) {

		$.ajax({
			   url: url+"?id="+sessionId,
			   data: $.JSON.encode(data),
			   success: function(msg){
					if ((msg+"").startsWith("ERROR")) {
						openMessageDialog(msg);
						callback(msg);
					}
					else {
						callback(msg);
					}
			}
	   });
	}

	function doSessionSynchronization(callback) {

		var callback1 = function() {
			sendCivilizationEventInformation(callback, civilizations_actions);
		};
		
		var data = new Object();
		for (var i=0;i<CIVILIZATIONS_ORDER.length;i++) {
			var civid = CIVILIZATIONS_ORDER[i];
			if (isCivilizationActive(civid)) {
				data[civid] = civilizations[civid];
			}
		}	
		sendCivilizationsInformation(callback1,data)
	}
	

	function fetchCivilizationEventsInformation(callback) {

		log("fetching civilization events information");

		if (sessionId!=null) {

			sendDataAjax(function (msg) {

				if ((msg+"").startsWith("ERROR")) {
				}
				else {
					for (var i=0;i<CIVILIZATIONS_ORDER.length;i++) {
						var civ = CIVILIZATIONS_ORDER[i];
						
						var newCiv = msg[civ];
						if (newCiv!=null) { 
							civilizations_actions[civ] = newCiv;
						}
					}
				}

				callback();

			},"","civaid/fetchCivilizationEvents");

		}
		else {
			callback();
		}
	}

	function fetchCivilizationInformation(callback) {

		log("fetching civilization information");

		if (sessionId!=null) {

			sendDataAjax(function (msg) {

				if ((msg+"").startsWith("ERROR")) {
				}
				else {
					for (var i=0;i<CIVILIZATIONS_ORDER.length;i++) {
						var civ = CIVILIZATIONS_ORDER[i];
						
						var newCiv = msg[civ];
						if (newCiv!=null) { 
							civilizations[civ] = newCiv;
						}
					}
				}

				callback();

			},"","civaid/fetchCivilizations");

		}
		else {
			callback();
		}
	}

	function formatCivilizationTitle(civid) {
		var player = civilizations[civid].player;
		var title = getCivilizationInformation(civid).name ;
		if (isCivilizationActive(civid)) title = title +" ("+ player+")";
		return title;
	}

	function getCivilizationCardGroups(cardid) {
		var card = getCivilizationCardInformation(cardid);
		var classes = new Array();
		
		if (parseInt(card.group) & craft_group) classes.push("craft");
		if (parseInt(card.group) & science_group) classes.push("science");
		if (parseInt(card.group) & art_group) classes.push("art");
		if (parseInt(card.group) & civic_group) classes.push("civic");
		if (parseInt(card.group) & religion_group) classes.push("religion");
		return classes;
	}
	
	function isCivilizationActive(civid) {
		var player = civilizations[civid].player;
		return typeof(player)!="undefined" && player.length>0;
	}
	

	function calculateSortedResultsList() {

		var list = new Array();
		var maxPoints = 0;
		for (var i=0;i<CIVILIZATIONS_ORDER.length;i++) {
			var civ = CIVILIZATIONS_ORDER[i];
			
			if (isCivilizationActive(civ)) {
				
				var p = calculateCardPoints(civ);
				var cp = calculateCivilizationPoints(civ);
				totalPoints = p.points+cp;
				list.push(new Object({civid:civ, cardPoints:p.points, civilizationPoints:cp, totalPoints: totalPoints, difference:0, cards:p.cards, groups: p.groups}));
				if (totalPoints>maxPoints) maxPoints = totalPoints;
			}
		}

		list.sort(function(r1,r2){return r2.totalPoints - r1.totalPoints;});

		for (i=0;i<list.length;i++) {
			list[i].difference = maxPoints-list[i].totalPoints;		
		}

		
		return list;
	}
	
	function calculateCivilizationPoints(civ) {
		var c = civilizations[civ]; 
		return (validateNumber(c.tradeGoodsPoints) + validateNumber(c.treasuryPoints) + validateNumber(c.citiesPoints) + validateNumber(c.astValuePoints));
	}
	
	function calculateCardPoints(civ) {

		var cardList = civilizations[civ].cards;
		var groupData=new Array();
		var totalPoints = 0;
		for (var i=0;i<cardList.length;i++) {
			var cardid = cardList[i];
			var card = getCivilizationCardInformation(cardid);
			totalPoints = totalPoints + card.value;
			var groups = getCivilizationCardGroups(cardid);
			for (var j =0;j<groups.length;j++) {
				if ($.inArray(groups[j],groupData)==-1) {
					groupData.push(groups[j]);		
				}
			}
		}
				
		return new Object({points: totalPoints, groups: groupData.length, cards: cardList.length});
	}
	
	var periodicalResultsUpdater=null
	
	function startPeriodicalResultsUpdater() {
		stopPeriodicalResultsUpdater()
		periodicalResultsUpdater=setTimeout(doResultsUIPeriodicalUpdate, 20000);

		log("started updater: "+periodicalResultsUpdater);
	}

	function stopPeriodicalResultsUpdater() {
		if (periodicalResultsUpdater!=null) {
			log("stopped updater: "+periodicalResultsUpdater);
			clearTimeout(periodicalResultsUpdater);
			periodicalResultsUpdater=null;
			
		}
	}
	
	function doResultsUIPeriodicalUpdate() {
		var rb = $("input#results-refresh-button");
		if (!rb.is(':visible') || rb.attr("checked")==false || sessionId==null) {
			log("ignored result updater");
		}
		else {
			log("refresh results");
			
			fetchCivilizationInformation(function() {
				
				showResultsTable();

				if (isResultsChartVisible()) {
					fetchCivilizationEventsInformation(function() {
						showResultsChart();
					});
				}
			});	
		}
		
		startPeriodicalResultsUpdater();
	}

	// RESULTS UI
	
	function updateResultsUI() {
		
		if (sessionId!=null) {
			$("input#results-refresh-button").show();
		}
		else {
			$("input#results-refresh-button").hide();
		}
		
		fetchCivilizationInformation(function() {
		
			showResultsTable();
			startPeriodicalResultsUpdater();
			
		});
	}

	function showResultsTable() {
		
		var container =$("table#results-container");
		container.empty();

		var list = calculateSortedResultsList();

		if (list.length>0) {
			$("button#show-results-chart-button").show();
			
			var showFinalPoints=false;
			for (var i=0;i<list.length;i++) {
				if (list[i].civilizationPoints>0) {
					showFinalPoints = true;
					break;
				}
			}

			if (showFinalPoints) 
				container.append($("<tr class='ui-state-default civilization-results-header'><th>Civilization</th><th>Final points</th><th>Total</th><th>Diff</th><th>Cards</th><th>C</th><th>G</th></tr>"));
			else 
				container.append($("<tr class='ui-state-default civilization-results-header'><th>Civilization</th><th>Total</th><th>Diff</th><th>C</th><th>G</th></tr>"));
			
			for (var i=0;i<list.length;i++) {
	
				var civid = list[i].civid;
				if (isCivilizationActive(civid)) {
					var c = civilizations[civid];
					var title = htmlEncode(formatCivilizationTitle(civid));
					var cardPoints = list[i].cardPoints;
					var civilizationPoints = list[i].civilizationPoints;
					var totalPoints = list[i].totalPoints;
					var difference = list[i].difference;
					var cards = list[i].cards;
					var groups = list[i].groups;
					
					var finalPointsTitle =(cardPoints+" + "+validateNumber(c.astValuePoints) +" + "+ validateNumber(c.citiesPoints) +" + "+ 
							validateNumber(c.treasuryPoints) + " + " + validateNumber(c.tradeGoodsPoints)+" = "+totalPoints); 
					
					title = (i+1)+". "+title;
	
					var civ = null;
					if (showFinalPoints) 
						civ = $('<tr class="civilization-results"><td class="civilization-results-title">'+title+'</td><td class="civilization-results-final-points">'+finalPointsTitle+'</td><td class="civilization-results-total-points">'+totalPoints+'</td><td class="civilization-results-points-difference">'+difference+'</td><td class="civilization-results-card-points">'+cardPoints+'</td><td class="civilization-results-cards-amount" >'+cards+'</td><td class="civilization-results-cards-groups" >'+groups+'</td></tr>');
					else
						civ = $('<tr class="civilization-results"><td class="civilization-results-title">'+title+'</td><td class="civilization-results-total-points">'+totalPoints+'</td><td class="civilization-results-points-difference">'+difference+'</td><td class="civilization-results-cards-amount" >'+cards+'</td><td class="civilization-results-cards-groups" >'+groups+'</td></tr>');

					container.append(civ);

					civ.addClass(civid);

				}
			}
		}
	}
	
	function storeResultsUI() {
		stopPeriodicalResultsUpdater();
		hideResultsChartEventTooltip();
		hideResultsChart();
		return true;
	}


	// RESULT UI CHART
		
	var resultsChartOptions = {

			cursor: {
			    showVerticalLine: true,
			    showHorizontalLine: true,
			    showCursorLegend: false,
			    showTooltip: true,
			    zoom: true,
			    dblClickReset: true,
			    intersectionThreshold: 6
			  },
	             
			axes:{
			    xaxis:{
			        renderer:$.jqplot.DateAxisRenderer, 
			        tickOptions:{formatString:'%H:%M'},
			        autoscale:false,
			        tickInterval:'1 hour'
			    },
			    yaxis:{
			        tickOptions:{formatString:'%i'},
			  	    autoscale:false
			    }
			}
			      
		};

	// SHOW CHART BUTTON
	
	$(function() {
		var showChartButton = $("button#show-results-chart-button").button();
		showChartButton.click(function () { 
			showChartButtonPressed();			
	    });

	});

	function isResultsChartVisible() {
		return $("div#results-chart").is(':visible');	
	}

	function showChartButtonPressed() {

		if (isResultsChartVisible()) {
			hideResultsChart();
			hideResultsChartEventTooltip();
		}
		else {
			fetchCivilizationEventsInformation(function() {

				showResultsChart();
			});
		}

	}
	
	$(function() {

		$.jqplot.config.enablePlugins = true;

		$.jqplot.eventListenerHooks.push(['jqplotClick', chartMouseClick]);	
		
	});

	
	function chartMouseClick (ev, gridpos, datapos, neighbor, plot) {
        if (neighbor == null) {
        	hideResultsChartEventTooltip();
        }
        else {
            var p = neighbor.pointIndex;
			
        	if (p>0) {
                var series = neighbor.seriesIndex;
                showResultsChartEventTooltip(series,p,ev);
            }
        }
    }
    function hideResultsChartEventTooltip() {
    	$('#chart-tooltip').hide().empty();
	}

	function showResultsChartEventTooltip(series, p, ev) {

        var civid = resultsChartOptions.series[series].label;
		var bgColor = resultsChartOptions.series[series].color;
		var civName = getCivilizationInformation(civid).name;
		var addedCards = "";
		var removedCards = "";

		var actions = civilizations_actions[civid];
		
		var addedList = actions[p-1].added;
		if (addedList.length>0) addedCards = "Added cards:<ul>";
		for (var a=0;a<addedList.length;a++) {
			addedCards = addedCards+"<li>"+getCivilizationCardInformation(addedList[a]).name+"</li>";
		}
		if (addedList.length>0) addedCards = addedCards + "</ul>";
		
		var removedList = actions[p-1].removed;
		if (removedList.length>0) removedCards = "Removed cards:<ul>";
		for (var a=0;a<removedList.length;a++) {
			removedCards = removedCards+"<li>"+getCivilizationCardInformation(removedList[a]).name+"</li>";
		}
		if (removedList.length>0) removedCards = removedCards + "</ul>";
		var points = actions[p-1].points;
		var cards = actions[p-1].cards;
		var tooltipText = "<b>"+civName+"</b> ("+p+") <br/>Points: "+points+"<br/>Cards: "+cards+"<br/>"+addedCards+removedCards;
        var tooltip = $('#chart-tooltip').html(tooltipText).css({'background-color':bgColor}).show();
        
        tooltip.position({
            my: "left top",
            of: ev,
            offset: "10 10",
            collision: "fit"
          });

	}

	function hideResultsChart() {
		$("div#results-chart").hide().empty();
		$("div#results-chart-title").hide().empty();

	}
	
	function showResultsChart() {
		
		var allValues = new Array();
		
		var minDate = new Date();
		var maxDate = new Date(0);
		var maxValue = 400;
		var k=0;

		var seriesConfigs = new Array();
		
		for (var i=0;i<CIVILIZATIONS_ORDER.length;i++) {
			var civ = CIVILIZATIONS_ORDER[i];
			
			if (isCivilizationActive(civ)) {

				var actions = civilizations_actions[civ];

				if (actions.length==0) continue;
				
				var clr = $("."+civ).css("background-color");
				seriesConfigs.push(new Object({label:civ, color:clr}))
				
				allValues[k] = new Array();
				allValues[k].push([new Date(actions[0].date),0]);
				
				for (var j=0;j<actions.length;j++) {
					var action = actions[j];
					var ad = new Date(action.date);
					if (ad<minDate) minDate = new Date(ad);
					if (ad>maxDate) maxDate = new Date(ad);
					if (action.points>maxValue) maxValue = action.points;
					
					allValues[k].push([ad,action.points]);
					 
				}
				
				k++;
			}
		}
		
		if (maxDate<minDate) maxDate = new Date(minDate);

		maxValue = (Math.round(maxValue/100)+1)*100;

		resultsChartOptions.series= seriesConfigs;
		minDate.setMinutes(0,0,0);
		resultsChartOptions.axes.xaxis.min=minDate;
		maxDate.setHours(maxDate.getHours()+1,0,0,0);
		resultsChartOptions.axes.xaxis.max=maxDate;
		resultsChartOptions.axes.yaxis.max=maxValue;
		resultsChartOptions.axes.yaxis.min=0;
		
		if (allValues.length==0) allValues = [[0,0]];

		var chartTitle = $("div#results-chart-title");
		chartTitle.html(formatDateTimeHours(minDate)+" - "+formatDateTimeHours(maxDate));
				
		var chartContainer = $("div#results-chart").empty();
		var resultsChart = $.jqplot('results-chart', allValues, resultsChartOptions);
		chartContainer.show();
		
		chartTitle.show();
		
		resultsChart.replot();

	}

	
	
	// MANAGE CIVILIZATIONS UI

	
	function storeManageCivilizationForm(civid) {

		var form =$("form#manage-civilization-form");

		var civData = getManageCivilizationValues(form);		
			
		var callback = function() { 
			var title = formatCivilizationTitle(civid);
	
			var c = $("a#manage-"+civid+"-title").text(title);
			var a = isCivilizationActive(civid);
			c.toggleClass(civid+"-disabled",!a);
			c.toggleClass(civid,a);
		}
		persistCivilizationInformation(civid, civData, callback);

	}

	function updateManageCivilizationForm(civid) {
		var form =$("form#manage-civilization-form");
		var m = $("div#manage-"+civid);
		m.empty();
		m.append(form);
		
		setManageCivilizationValues(form, civid);
		var inp = form.find("input#manage-civilization-name");
		inp.unbind('keypress');
		inp.keypress(function(event) {
			  if (event.which == '13') {
			     event.preventDefault();
			     storeManageCivilizationForm(civid);
			  }
		});
		form.show();
		inp.focus(10);
	}

	function setManageCivilizationValues(form, civid) {
		var info = civilizations[civid];
		
		form.find("input#manage-civilization-name").val(info.player);
		form.find("select#manage-civilization-ast-value").val(info.astValuePoints);
		form.find("select#manage-civilization-cities").val(info.citiesPoints);
		form.find("input#manage-civilization-treasury").val(info.treasuryPoints);
		form.find("input#manage-civilization-trade-goods").val(info.tradeGoodsPoints);
	}
	
	function getManageCivilizationValues(form) {
		var info = new Object();
		info.player = $.trim(form.find("input#manage-civilization-name").val());
		info.astValuePoints = validateNumber(form.find("select#manage-civilization-ast-value").val());
		info.citiesPoints = validateNumber(form.find("select#manage-civilization-cities").val());
		info.treasuryPoints = validateNumber(form.find("input#manage-civilization-treasury").val());
		info.tradeGoodsPoints = validateNumber(form.find("input#manage-civilization-trade-goods").val());
		return info;
	}
	
	function updateManageCivilizationsUI() {

		selectedManageCivilization=null;
		var accordion = $("#manage-civilizations-accordion").accordion("activate",false);
		
		fetchCivilizationInformation(function() {
		
			for (var i=0;i<CIVILIZATIONS_ORDER.length;i++) {
				var civid = CIVILIZATIONS_ORDER[i];
				var title = formatCivilizationTitle(civid);
	
				var c = accordion.find("a#manage-"+civid+"-title").text(title);
				var a = isCivilizationActive(civid);
				c.toggleClass(civid+"-disabled",!a);
				c.toggleClass(civid,a);
			}
		});
		
	}

	function storeManageCivilizationsUI() {

		$("form#manage-civilization-form").hide();
		var accordion = $("#manage-civilizations-accordion").accordion("activate",false);
		
		if (selectedManageCivilization!=null) {
			storeManageCivilizationForm(selectedManageCivilization);
		}
		return true;
	}


	// BUY CARDS UI

	function storeBuyCardsForm(civid) {

		var cards = getCurrentlySelectedCards();
		closePointsDialog();
		persistSelectedCards(civid, cards, function(){});

	}

	function getCurrentlySelectedCards() {
		var form =$("form#buy-cards-form");

		var selected = form.serializeArray();
		var cards = new Array();
		for (var i = 0;i<selected.length;i++) {
			var cardid = selected[i].name.split("-")[1];
			cards.push(cardid);
		}
		return cards;
	}

	function updateBuyCardsForm(civid) {
		var form =$("form#buy-cards-form");
		var m = $("div#buy-"+civid);
		m.empty();
		m.append(form);
	
		form.show();		

		initializeBuyCards(civid);

		showPointsDialog();
		
	}
	
	function buyCardButtonStatusChanged(cardButton) {

		var cardid = cardButton.attr("id").split("-")[1];
		var isSelected = cardButton.attr("checked");
		
		var form =$("form#buy-cards-form");

		var values = getPointsDialogValues();
		var newTotalCost = values[0];
		var newTotalPoints = values[1];
		var currentPoints = values[2];

		var card = getCivilizationCardInformation(cardid);
		var container = form.find("table#cardid-container-"+cardid);

		var price = validateNumber(container.find("td#cardprice-"+cardid).text());

		if (isSelected==true) {
			newTotalPoints=newTotalPoints+card.value;
			if (container.hasClass("civilization-card-available")) {
				newTotalCost=newTotalCost+price;
			}
		}
		else {
			newTotalPoints=newTotalPoints-card.value;
			newTotalCost=newTotalCost-price;
		}

		log(newTotalCost+" : "+newTotalPoints+" : "+currentPoints);
		
		setPointsDialogValues(newTotalCost, newTotalPoints, currentPoints);
	}

	function setBuyCardButtonStatus(button, selected, disabled) {

		if (disabled) {
			button.attr("disabled",true);
			button.attr("checked",false);
		}
		else {
			button.attr("disabled",false);
			button.attr("checked",selected);

		}
	}


	function initializeBuyCards(civid) {
		var form =$("form#buy-cards-form");

		var currentCards = civilizations[civid].cards;

		var totalPoints = 0;
		
		for (var i=0;i<CIVILIZATION_CARDS_ORDER.length;i++) {
			var cardid = CIVILIZATION_CARDS_ORDER[i];
			var container = form.find("table#cardid-container-"+cardid);
						
			var card = getCivilizationCardInformation(cardid);
			
			var alreadyBought =containsCard(currentCards, cardid); 
			var allowedToBuy = true;
			var cardPriceField = container.find("td#cardprice-"+cardid);
			container.removeClass("civilization-card-not-available civilization-card-available civilization-card-already-bought" );

			if (alreadyBought) {
				totalPoints=totalPoints+card.value;
				cardPriceField.text(0);
				container.toggleClass("civilization-card-already-bought", true);
					
			}
			else {
								
				var priceField = getCardRequirement(cardid, currentCards);
				if (priceField!=null) {
					allowedToBuy = false;
					priceField = priceField.substring(0,Math.min(4,priceField.length));

					container.toggleClass("civilization-card-not-available", true);
						
				}
				else {
					allowedToBuy = true;
					priceField = calculateCardPrice(cardid, currentCards);
					container.toggleClass("civilization-card-available", true);
					
				}
				cardPriceField.text(priceField);
			}

			container.find("td#cardvalue-"+cardid).text(card.value);

			var cardButton = container.find("input#cardid-"+cardid);
			
			// start test
			cardButton.unbind("click");
			cardButton.click( function(event) {
				event.stopPropagation();
				buyCardButtonStatusChanged($(this));
			});

			var buttonTd = cardButton.closest("td");
			buttonTd.unbind("click");
			buttonTd.click( function(event) {
				event.stopPropagation();
				var input = $(this).find("input");
				if (input.attr("disabled") == false) {
					input.attr("checked", !input.attr("checked"));
					buyCardButtonStatusChanged(input);
				}
			});
			// end test
			setBuyCardButtonStatus(cardButton, alreadyBought, !allowedToBuy);
			
		}
		setPointsDialogValues(0,totalPoints, totalPoints);

	}


	function containsCard(cardIdList, cardId) {
		return $.inArray(cardId,cardIdList)!=-1;
	}


	function getCardRequirement(cardid,cards) {
		var card = getCivilizationCardInformation(cardid);
		var req = card.required;
		if (req!=null && typeof(req)!="undefined")  {
			if (!containsCard(cards, req)) return getCivilizationCardInformation(req).name;
		}

		return null;
	}
	
	function calculateCardPrice(cardid, cards) {

		var card = getCivilizationCardInformation(cardid);
		var price = card.value;

		var discounts = getCivilizationCardDiscounts(cardid);
		for (var i=0;i<cards.length;i++) {
			var bd = cards[i];
			var index = $.inArray(bd,CIVILIZATION_CARDS_ORDER);
			var d = discounts[index];
			if (typeof(d)!="undefined") {
				price = price - d;
			}
		}
		
		if (price<0) price=0;
		return price;
	}


	function updateBuyCardsUI() {

		selectedBuyCardsCivilization=null;
		var accordion = $("#buy-cards-accordion").accordion("activate",false);

		fetchCivilizationInformation(function() {
		
			for (var i=0;i<CIVILIZATIONS_ORDER.length;i++) {
				var civid = CIVILIZATIONS_ORDER[i];
	
				if (isCivilizationActive(civid)) {
	
					var title = formatCivilizationTitle(civid);
					accordion.find("a#buy-"+civid+"-title").text(title);
	
					accordion.find( ".ui-accordion-header:eq("+i+")" ).show();
				}
				else {
					accordion.find( ".ui-accordion-header:eq("+i+")" ).hide();
				}
			}
		});

	}

	function storeBuyCardsUI() {

		$("form#buy-cards-form").hide();
		var accordion = $("#buy-cards-accordion").accordion("activate",false);
		
		if (selectedBuyCardsCivilization!=null) {
			storeBuyCardsForm(selectedBuyCardsCivilization);
		}
		return true;
	}


	

	// POINTS DIALOG

	function showPointsDialog() {
		$("div#buy-cards-dialog").dialog("open");

	}

	function setPointsDialogValues(newTotalCost, newTotalPoints, currentPoints) {

		var dialog =$("div#buy-cards-dialog");

		var ncost= dialog.find("#new-total-cost");
		ncost.text(newTotalCost);

		var npoints = dialog.find("#new-total-points");
		npoints.text(newTotalPoints);
		
		var cpoints = dialog.find("#current-points");
		cpoints.text(currentPoints);

	}
	
	function getPointsDialogValues() {

		var dialog =$("div#buy-cards-dialog");
		
		var ncost= dialog.find("#new-total-cost");
		var ntc = validateNumber(ncost.text());

		var npoints = dialog.find("#new-total-points");
		var ntp = validateNumber(npoints.text());
		
		var cpoints = dialog.find("#current-points");
		var cp = validateNumber(cpoints.text());	

		return new Array(ntc, ntp, cp);
	}
	
	function closePointsDialog() {
		$( "div#buy-cards-dialog" ).dialog("close");
	}
	

	// START
	
	$(function() {

		$( "#tabs" ).tabs({
			selected:2
		});
		
		updateManageCivilizationsUI();
		$("#main-ui").show();
		$("div#progress-field").hide();
	});

